﻿using LineOfBusiness.Controls.Base;
using LineOfBusiness.Core.Base;
using LineOfBusiness.Core.Helper;
using LineOfBusiness.Core.Utilities;
using LineOfBusiness.DataAccess;
using LineOfBusiness.Poco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LineOfBusiness.AD.Controllers
{
    [PageAttribute(EntityChild = "AD_tblUserGroup", EntityMater = "AD_tblUserAccount")]
    public class UserAccountController : LOBController
    {
        public UserAccountController()
        {
            this.GridViewName = "grvtblUserAccount";
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Add()
        {
            ViewBag.Edit = 0;
            AD_tblUserAccount UserAccount = new AD_tblUserAccount();


            if (ViewData.ContainsKey(ViewDataKeys.Predicate))
                ViewData.Remove(ViewDataKeys.Predicate);

            if (ViewData.ContainsKey(ViewDataKeys.DataValue))
                ViewData.Remove(ViewDataKeys.DataValue);

            return View("Input", UserAccount);
        }

        public ActionResult View(string UserGroupID)
        {
            using(EFDALContainer dal = new EFDALContainer())
            {
                AD_tblUserAccount UserAccount = dal.Repository.GetQuery<AD_tblUserAccount>().Where(o => o.UserGroupID == UserGroupID).FirstOrDefault();
                ViewBag.Edit = -1;
                return View("Input", UserAccount);
            }
        }

        public ActionResult Edit(string UserGroupID)
        {
            using (EFDALContainer dal = new EFDALContainer())
            {
                AD_tblUserAccount UserAccount = dal.Repository.GetQuery<AD_tblUserAccount>().Where(o => o.UserGroupID == UserGroupID).FirstOrDefault();
                if (this.Request.QueryString.AllKeys.Contains("View"))
                    ViewBag.Edit = -1;
                else
                    ViewBag.Edit = 1;

                return View("Input", UserAccount);
            }
        }

        [HttpPost]
        public ActionResult Delete(AD_tblUserAccount UserAccount)
        {
            using (EFDALContainer dal = new EFDALContainer())
            {
                try
                {
                    dal.Repository.Delete(UserAccount);
                    dal.UnitOfWork.SaveChanges();
                }
                catch (Exception exp)
                {
                    return Json(exp.Message);
                }
                return Json("0");
            }
        }

        [HttpPost]
        public ActionResult Save(object UserAccount)
        {
            string method = "Edit";
            string KeyOld = "";

            if (ViewData["Edit"].Equals("0"))
            {
                method = "Add";
            }
            else
            {
                KeyOld = ViewData["ID"] as string;
            }

            if (UserAccount != null)
            {
                foreach (var item in (UserAccount as AD_tblUserAccount).AD_tblUserGroup)
                {
                    item.UserID = (UserAccount as AD_tblUserAccount).UserGroupID;
                }
            }
            var SetupUserGroups = (UserAccount as AD_tblUserAccount);
            using (EFDALContainer dal = new EFDALContainer())
            {
                try
                {
                    if( method == "Add")
                    {
                        if (!SetupUserGroups.FGroup)
                        {
                            var p = dal.Repository.GetOne<AD_tblUserAccountPolicy>(o => 1 == 1);
                            if (p.StrongSecurity)
                            {
                                if (SetupUserGroups.Password == null || p.MinimunPwdLen > SetupUserGroups.Password.Length)
                                {
                                    return Json(string.Format(LOBHelper.GetMessage("PasswordLargerMin", "Lenght of password must large {0}"),p.MinimunPwdLen));
                                }
                            }

                            SetupUserGroups.Password = SetupUserGroups.Password ?? "";
                            SetupUserGroups.Password = (new LVCrypto()).Encrypt(SetupUserGroups.Password + SetupUserGroups.UserGroupID.ToLower());
                        }

                        if (SetupUserGroups.AD_tblUserGroup != null && SetupUserGroups.AD_tblUserGroup.Count > 0)
                        {
                            foreach (var item in SetupUserGroups.AD_tblUserGroup)
                            {
                                dal.Repository.Add(item);
                            }
                        }
                        SetupUserGroups.AD_tblUserGroup = null;
                        AD_tblUserAccountPwdHistory h = new AD_tblUserAccountPwdHistory() { OldPassword = "", UserGroupID = SetupUserGroups.UserGroupID, DateChanged = DateTime.Now };
                        dal.Repository.Add(h);
                        dal.Repository.Add(SetupUserGroups);
                    }
                    else
                    {
                        var user = dal.Repository.GetQuery<AD_tblUserAccount>().Where(o => o.UserGroupID == SetupUserGroups.UserGroupID).FirstOrDefault();


                        if (!SetupUserGroups.FGroup && user.Password != SetupUserGroups.Password)
                        {
                            var p = dal.Repository.GetOne<AD_tblUserAccountPolicy>(o => 1 == 1);
                            if (p.StrongSecurity)
                            {
                                if (SetupUserGroups.Password == null || p.MinimunPwdLen > SetupUserGroups.Password.Length)
                                {
                                    return Json(string.Format(LOBHelper.GetMessage("PasswordLargerMin", "Lenght of password must large {0}"), p.MinimunPwdLen));
                                }
                            }

                            AD_tblUserAccountPwdHistory h = new AD_tblUserAccountPwdHistory() { OldPassword = user.Password, UserGroupID = SetupUserGroups.UserGroupID, DateChanged = DateTime.Now };
                            dal.Repository.Add(h);

                            SetupUserGroups.Password = SetupUserGroups.Password ?? "";
                            SetupUserGroups.Password = (new LVCrypto()).Encrypt(SetupUserGroups.Password + SetupUserGroups.UserGroupID.ToLower());
                        }



                        if (KeyOld == SetupUserGroups.UserGroupID)
                        {
                            dal.Repository.Update(SetupUserGroups);
                            if (SetupUserGroups.AD_tblUserGroup != null)
                            {
                                if (SetupUserGroups.FGroup)
                                    dal.Repository.Delete<AD_tblUserGroup>(o => o.GroupID == SetupUserGroups.UserGroupID);
                                else
                                    dal.Repository.Delete<AD_tblUserGroup>(o => o.UserID == SetupUserGroups.UserGroupID);

                                foreach (var item in SetupUserGroups.AD_tblUserGroup)
                                {
                                    dal.Repository.Add(item);
                                }
                            }
                        }
                        else
                        {
                            if (SetupUserGroups.AD_tblUserGroup != null) dal.Repository.Delete<AD_tblUserAccount>(o => o.UserGroupID == KeyOld);
                            dal.Repository.Add(SetupUserGroups);
                        }
                    }

                    dal.UnitOfWork.SaveChanges();
                }
                catch (Exception exp)
                {
                    return Json(exp.Message);
                }
                return Json("0");
            }
           
        }

        public ActionResult UpdateAdmin(string UserGroupID)
        {
           using(EFDALContainer dal = new EFDALContainer())
           {
               var user = dal.Repository.GetOne<AD_tblUserAccount>(o => o.UserGroupID == UserGroupID);
                if (user != null)
                {
                    user.FAdm = !user.FAdm;
                    dal.Repository.Update(user);
                    dal.UnitOfWork.SaveChanges();
                }
           }

           return Json(new { Error = "" }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ReSetPassword(string UserGroupID)
        {
            using (EFDALContainer dal = new EFDALContainer())
            {
                AD_tblUserAccount UserAccount = dal.Repository.GetQuery<AD_tblUserAccount>().Where(o => o.UserGroupID == UserGroupID).FirstOrDefault();
                return View(UserAccount);
            }

        }

        public ActionResult UpdateReSetPassword(string UserGroupID, string Password)
        {
            AD_tblUserAccount UserAccount = null;
            using (EFDALContainer dal = new EFDALContainer())
            {
                UserAccount = dal.Repository.GetQuery<AD_tblUserAccount>().Where(o => o.UserGroupID == UserGroupID).FirstOrDefault();
            }
            UserAccount.Password = Password;
            ViewData["Edit"] = "1";
            ViewData["ID"] = UserAccount.UserGroupID;

            JsonResult result = (JsonResult)Save(UserAccount);
            return result;
        }

        public ActionResult ChangePassword()
        {
            return View();
        }

        public ActionResult UpdateChangePassword(string PasswordOld, string PasswordNew)
        {
            using (EFDALContainer dal = new EFDALContainer())
            {
                try
                {
                    var user = dal.Repository.GetOne<AD_tblUserAccount>(o => o.UserGroupID == CacheHelper.LoginUser.UserID);

                    if (user != null)
                    {
                        if ((new LVCrypto()).Decrypt(user.Password) != (PasswordOld + user.UserGroupID.ToLower()))
                        {
                            return Json(LOBHelper.GetMessage("OldPassWordIncorrect", "Old PassWord Incorrect"));
                        }

                        var p = dal.Repository.GetOne<AD_tblUserAccountPolicy>(o => 1 == 1);
                        if (p.StrongSecurity)
                        {
                            if (p.MinimunPwdLen > PasswordNew.Length)
                            {
                                Json(new { Error = string.Format(LOBHelper.GetMessage("PasswordLargerMin", "Lenght of password must large {0}"), p.MinimunPwdLen) }, JsonRequestBehavior.AllowGet);
                            }
                        }



                        user.Password = (new LVCrypto()).Encrypt(PasswordNew + user.UserGroupID.ToLower());
                        user.MustChangePwd = false;

                        AD_tblUserAccountPwdHistory h = new AD_tblUserAccountPwdHistory() { OldPassword = user.Password, UserGroupID = CacheHelper.LoginUser.UserID, DateChanged = DateTime.Now };
                        dal.Repository.Add(h);

                        dal.Repository.Update(user);
                        dal.UnitOfWork.SaveChanges();
                    }
                }
                catch (Exception exp)
                {
                    return Json(new { Error = exp.Message }, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(new { Error = "0" }, JsonRequestBehavior.AllowGet);
        }

    }
}